package main

import (
	"encoding/hex"
	"encoding/json"
	"net/http"
	"strconv"
)

func messageSendBackClient(d Message, w http.ResponseWriter, ostype int) {
	jsonMessage, _ := json.Marshal(&Message{P: d.P, D: d.D, C: d.C, O: d.O, E: d.E, I: d.I})
	//MyPrintf("server back 2: %s \n", jsonMessage)
	if ostype == 2 {
		httpMessageSendToClient(d, w)
	} else {
		manager.broadcast <- jsonMessage
	}
}

func messageDoWork(js ClientJSONData, c *Client, w http.ResponseWriter, ostype int) {
	MyPrintf("\n messageDoWork js: %s \n", js)
	if js.C == "version" {
		getVersion(w, ostype)
		return
	}
	if js.C == "se.list" {
		getSerialList(w, ostype)
		return
	}
	if js.C == "se.open" {
		baud, err := strconv.Atoi(js.D)
		if err != nil {
			baud = 115200
		}
		cid := ""
		if c != nil {
			cid = c.id
		}
		serialOpen(js.P, baud, cid, w, ostype)
		return
	}
	if js.C == "se.close" {
		serialClose(js.P, w, ostype)
		messageSendBackClient(Message{P: js.P, C: js.C, D: "ok"}, w, ostype)
		return
	}
	if js.C == "se.write" {
		data, err := hex.DecodeString(js.D)
		if err != nil {
			MyPrintf("-sendhex-error: %v \n", err)
			return
		}
		serialWrite(js.P, data, w, ostype)
	}
	if js.C == "se.uphex" {
		SerialUploadHexByLocal(js.D, js.P, w, ostype)
		return
	}
	if js.C == "se.yunhexup" {
		serialYunHexUp(js.P, js.D, js.O, w, ostype)
		return
	}
	if js.C == "se.ssh" {
		execShellCommer(js.D, w, ostype)
		return
	}
	if js.C == "se.upino" {
		SerialUpInoByLocalIDE(js.P, js.D, js.O, js.E, w, ostype)
		return
	}
	if js.C == "se.yuninoup" {
		SerialUpInoByYun(js.P, js.D, js.O, js.E, w, ostype)
		return
	}
	if js.C == "sv.hexback" {
		serialInoCreatHex(js.D, js.O, w, ostype)
		return
	}
}

func getVersion(w http.ResponseWriter, ostype int) {
	msg := Message{D: SY.Version, C: "version"}
	messageSendBackClient(msg, w, ostype)
}
